﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Device
{
    /// <summary>
    /// 设备管理
    /// </summary>
    public class DeviceManage
    {
        /// <summary>
        /// 获取实现列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<DeviceDetails> GetImplementationS<T>(string path)
        {
            var fileS = FolderHelper.GetFileNames(path);
            List<DeviceDetails> result = new List<DeviceDetails>();
            // 获取Description特性 
            Type typeDescription = typeof(DescriptionAttribute);

            foreach (var item in fileS)
            {
                try
                {
                    var ext = item.Substring(item.LastIndexOf(".", StringComparison.Ordinal));
                    if (ext.Equals(".dll")|| ext.Equals(".exe"))
                    {
                        var data = Assembly.LoadFile(item).GetTypes();
                        foreach (var t in data)
                        {
                            if (t.GetInterface((typeof(T).ToString())) != null)
                            {
                                object[] array = t.GetCustomAttributes(typeDescription, false);
                                var text = array.Length > 0 ? ((DescriptionAttribute)array[0]).Description : t.Name;

                                result.Add(new DeviceDetails()
                                {
                                    // FilePath = item,
                                    Namespace = t.Namespace,
                                    Name = t.Name,
                                    Text = text
                                });

                            }

                        }
                    }
                }
                catch (Exception)
                {
                    //
                }

            }
            return result;
        }
        //public static T GetImplementation<T>(string name, string connectString)
        //{
        //    return GetImplementation<T>(name );
        //}
        /// <summary>
        /// 获取实体象
        /// </summary> 
        /// <returns></returns>/
        public static T GetImplementation<T>(string name )
        {
            //var tmp = Assembly.LoadFile(path).GetTypes();
            var tmp = typeof(T).Assembly.GetTypes();
            Type t = tmp.FirstOrDefault(s => s.Name == name);
            if (t != null)
            {
                // T result = (T)Activator.CreateInstance(t, args);
                T result = (T)Activator.CreateInstance(t);
                return result;
            }
            return default(T);
        }
        /// <summary>
        /// 获取子类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<string> GetSubclass<T>(string path) where T : class
        {
            var fileS = FolderHelper.GetFileNames(path);
            List<string> result = new List<string>();
            foreach (var item in fileS)
            {
                try
                {
                    var ext = item.Substring(item.LastIndexOf(".", StringComparison.Ordinal));
                    if (ext.Equals(".dll"))
                    {
                        var data = Assembly.LoadFile(item).GetTypes()
                            .Where(s => s.IsSubclassOf(typeof(T)));
                        result.AddRange(data.Select(s => s.Name));
                    }

                }
                catch (Exception)
                {
                    // ignored
                }
            }
            return result;
        }
    }


    public class DeviceDetails
    {
        /// <summary>
        /// 命名空间
        /// </summary>
        public string Namespace { get; set; }
        /// <summary>
        /// 名字
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 显示
        /// </summary>
        public string Text { get; set; }
        ///// <summary>
        ///// 文件路径
        ///// </summary>
        //public string FilePath { get; set; }
    }


    /// <summary>
    /// 文件夹帮助类
    /// </summary>
    public class FolderHelper
    {
        /// <summary>
        /// 是否存在文件夹
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <returns></returns>
        public static bool IsExistDirectory(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }
        /// <summary>
        /// 创建一个目录
        /// </summary>
        /// <param name="directoryPath">目录的绝对路径</param>
        public static bool CreateDirectory(string directoryPath)
        {
            //如果目录不存在则创建该目录
            if (!IsExistDirectory(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            return true;
        }

        /// <summary>
        /// 获取指定目录中所有文件列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>        
        public static string[] GetFileNames(string directoryPath)
        {
            //如果目录不存在，则抛出异常
            if (!IsExistDirectory(directoryPath))
            {
                throw new FileNotFoundException();
            }

            //获取文件列表
            return Directory.GetFiles(directoryPath);
        }

    }
}
